package com.mjx.service;

import com.mjx.Util.KeyUtil;
import com.mjx.controller.MyWebSocket;
import com.mjx.dao.UserRepository;
import com.mjx.entity.Message;
import com.mjx.entity.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.Session;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * Created by meijingxiang on 2017/3/9.
 */
@Service
public class ChatService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    UserService userService;

    @Autowired
    UserRepository userRepository;

    /**
     * 保存消息记录
     * @param from
     * @param content
     * @param conversationId
     */
    public void saveMessage(User from, String content, String conversationId){
        Message message = new Message();
        message.setContent(content);
        if (StringUtils.isEmpty(conversationId))
            conversationId = KeyUtil.getConversationId();
        message.setConversationId(conversationId);
        message.setCreateTime(new Date());
        message.setFromUser(from);
        mongoTemplate.save(message);
    }

    /**
     * 发送消息（单）
     * @param session
     * @param message
     * @param from
     * @param conversationId
     * @throws IOException
     */
    public void sendMessage(Session session, String message, User from, String conversationId) throws IOException {
        this.saveMessage(from, message, conversationId);

        session.getBasicRemote().sendText(packageMessage(from, message));
    }

    /**
     * 发送消息（群）
     * @param webSockets
     * @param message
     * @param from
     * @param conversationId
     * @throws IOException
     */
    public void sendMessage(CopyOnWriteArraySet<MyWebSocket> webSockets, String message, User from, String conversationId) throws IOException {
        this.saveMessage(from, message, conversationId);
        Iterator<MyWebSocket> iterator = webSockets.iterator();
        while (iterator.hasNext()){
            MyWebSocket myWebSocket = iterator.next();
            myWebSocket.getSession().getBasicRemote().sendText(packageMessage(from, message));
        }
    }

    /**
     * 登录操作
     * @param name
     * @param request
     * @return
     */
    public User login(String name, HttpServletRequest request){
        User user = new User();
        String ip = this.getRemoteHost(request);
        user.setClientIp(ip);
        user.setName(name);
        return userService.saveUser(user);
    }

    /**
     * 检查ip是否已经注册过
     * @param request
     * @return
     */
    public User checkIpExists(HttpServletRequest request){
        String ip = this.getRemoteHost(request);
        return userRepository.findByClientIp(ip);
    }

    /**
     * 包装消息
     * @param from
     * @param message
     * @return
     */
    private String packageMessage(User from, String message){
        message = from.getName() + " : " + message;
        return message;
    }

    /**
     * 根据request获得客户端ip
     * @param request
     * @return
     */
    private String getRemoteHost(HttpServletRequest request){
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
    }
}
